<template>
  <view class="profile-container">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-avatar">
        <text class="avatar-text">😊</text>
      </view>
      <view class="user-info">
        <text class="user-name">情绪大师用户</text>
        <text class="user-desc">已使用 {{ usageDays }} 天</text>
      </view>
      <view class="user-stats">
        <view class="stat-item">
          <text class="stat-number">{{ totalRecords }}</text>
          <text class="stat-label">记录数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ totalTests }}</text>
          <text class="stat-label">测评次数</text>
        </view>
      </view>
    </view>

    <!-- 成就徽章 -->
    <view class="achievement-section">
      <view class="section-title">成就徽章</view>
      <scroll-view scroll-x class="badge-list">
        <view class="badge-item" v-for="badge in badges" :key="badge.id" :class="{ unlocked: badge.unlocked }">
          <view class="badge-icon">
            <text class="badge-emoji">{{ badge.emoji }}</text>
          </view>
          <text class="badge-name">{{ badge.name }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 功能菜单 */
    <view class="menu-section">
      <view class="menu-item" @tap="goToHistory">
        <view class="menu-icon">
          <text class="iconfont icon-chart">📊</text>
        </view>
        <view class="menu-content">
          <text class="menu-title">数据统计</text>
          <text class="menu-desc">查看详细的情绪数据分析</text>
        </view>
        <view class="menu-arrow">
          <text class="iconfont icon-arrow">→</text>
        </view>
      </view>

      <view class="menu-item" @tap="goToFavorites">
        <view class="menu-icon">
          <text class="iconfont icon-heart">❤️</text>
        </view>
        <view class="menu-content">
          <text class="menu-title">我的收藏</text>
          <text class="menu-desc">收藏的课程和内容</text>
        </view>
        <view class="menu-arrow">
          <text class="iconfont icon-arrow">→</text>
        </view>
      </view>

      <view class="menu-item" @tap="toggleDarkMode">
        <view class="menu-icon">
          <text class="iconfont icon-theme">🌙</text>
        </view>
        <view class="menu-content">
          <text class="menu-title">夜间模式</text>
          <text class="menu-desc">保护眼睛，舒适体验</text>
        </view>
        <switch :checked="isDarkMode" @change="onDarkModeChange" class="menu-switch" />
      </view>

      <view class="menu-item" @tap="showDataManagement">
        <view class="menu-icon">
          <text class="iconfont icon-data">💾</text>
        </view>
        <view class="menu-content">
          <text class="menu-title">数据管理</text>
          <text class="menu-desc">备份、清理本地数据</text>
        </view>
        <view class="menu-arrow">
          <text class="iconfont icon-arrow">→</text>
        </view>
      </view>

      <view class="menu-item" @tap="showAbout">
        <view class="menu-icon">
          <text class="iconfont icon-info">ℹ️</text>
        </view>
        <view class="menu-content">
          <text class="menu-title">关于应用</text>
          <text class="menu-desc">版本信息和使用帮助</text>
        </view>
        <view class="menu-arrow">
          <text class="iconfont icon-arrow">→</text>
        </view>
      </view>
    </view>

    <!-- 数据管理弹窗 -->
    <uni-popup ref="dataPopup" type="bottom">
      <view class="data-popup">
        <view class="popup-header">
          <text class="popup-title">数据管理</text>
          <view class="popup-close" @tap="closeDataPopup">
            <text class="iconfont icon-close">✖️</text>
          </view>
        </view>
        <view class="popup-content">
          <!-- <view class="data-item" @tap="exportData">
            <text class="data-title">导出数据</text>
            <text class="data-desc">将数据导出为文件备份</text>
          </view> -->
          <view class="data-item" @tap="clearData">
            <text class="data-title">清理数据</text>
            <text class="data-desc">清除所有本地存储的数据</text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      usageDays: 0,
      totalRecords: 0,
      totalTests: 0,
      isDarkMode: false,
      badges: [
        { id: 1, name: '初次记录', emoji: '📝', unlocked: false },
        { id: 2, name: '连续7天', emoji: '🔥', unlocked: false },
        { id: 3, name: '情绪稳定', emoji: '😌', unlocked: false },
        { id: 4, name: '测评达人', emoji: '🎯', unlocked: false },
        { id: 5, name: '冥想新手', emoji: '🧘', unlocked: false },
        { id: 6, name: '坚持30天', emoji: '💪', unlocked: false }
      ]
    }
  },
  
  onLoad() {
    this.loadUserData()
    this.loadSettings()
    this.checkAchievements()
  },
  
  onShow() {
    this.loadUserData()
    this.checkAchievements()
  },
  
  methods: {
    // 加载用户数据
    loadUserData() {
      try {
        // 计算使用天数
        const firstUse = uni.getStorageSync('first_use_date')
        if (firstUse) {
          const days = Math.floor((Date.now() - new Date(firstUse).getTime()) / (1000 * 60 * 60 * 24))
          this.usageDays = Math.max(1, days)
        } else {
          this.usageDays = 1
          uni.setStorageSync('first_use_date', new Date().toISOString())
        }
        
        // 统计记录数
        const moodRecords = uni.getStorageSync('mood_records') || []
        this.totalRecords = moodRecords.length
        
        // 统计测评次数
        const testHistory = uni.getStorageSync('test_history') || []
        this.totalTests = testHistory.length
        
      } catch (e) {
        console.error('加载用户数据失败:', e)
      }
    },
    
    // 加载设置
    loadSettings() {
      try {
        this.isDarkMode = uni.getStorageSync('dark_mode') || false
      } catch (e) {
        console.error('加载设置失败:', e)
      }
    },
    
    // 检查成就
    checkAchievements() {
      try {
        const achievements = uni.getStorageSync('achievements') || []
        
        // 检查各种成就条件
        if (this.totalRecords > 0) {
          this.unlockBadge(1) // 初次记录
        }
        
        if (this.usageDays >= 7) {
          this.unlockBadge(2) // 连续7天
        }
        
        if (this.totalTests >= 5) {
          this.unlockBadge(4) // 测评达人
        }
        
        if (this.usageDays >= 30) {
          this.unlockBadge(6) // 坚持30天
        }
        
        // 更新徽章状态
        this.badges.forEach(badge => {
          badge.unlocked = achievements.includes(badge.id)
        })
        
      } catch (e) {
        console.error('检查成就失败:', e)
      }
    },
    
    // 解锁徽章
    unlockBadge(badgeId) {
      try {
        let achievements = uni.getStorageSync('achievements') || []
        if (!achievements.includes(badgeId)) {
          achievements.push(badgeId)
          uni.setStorageSync('achievements', achievements)
          
          const badge = this.badges.find(b => b.id === badgeId)
          if (badge) {
            uni.showToast({
              title: `获得成就：${badge.name}`,
              icon: 'success'
            })
          }
        }
      } catch (e) {
        console.error('解锁徽章失败:', e)
      }
    },
    
    // 跳转到历史统计
    goToHistory() {
      uni.navigateTo({
        url: '/pages/profile/stats'
      })
    },
    
    // 跳转到收藏
    goToFavorites() {
      uni.navigateTo({
        url: '/pages/profile/favorites'
      })
    },
    
    // 切换夜间模式
    toggleDarkMode() {
      this.isDarkMode = !this.isDarkMode
      this.saveDarkMode()
    },
    
    // 夜间模式开关变化
    onDarkModeChange(e) {
      this.isDarkMode = e.detail.value
      this.saveDarkMode()
    },
    
    // 保存夜间模式设置
    saveDarkMode() {
      try {
        uni.setStorageSync('dark_mode', this.isDarkMode)
        uni.showToast({
          title: this.isDarkMode ? '已开启夜间模式' : '已关闭夜间模式',
          icon: 'success'
        })
      } catch (e) {
        console.error('保存设置失败:', e)
      }
    },
    
    // 显示数据管理弹窗
    showDataManagement() {
      this.$refs.dataPopup.open()
    },
    
    // 关闭数据管理弹窗
    closeDataPopup() {
      this.$refs.dataPopup.close()
    },
    
    // 导出数据
    exportData() {
      uni.showModal({
        title: '导出数据',
        content: '此功能将在后续版本中提供',
        showCancel: false
      })
      this.closeDataPopup()
    },
    
    // 清理数据
    clearData() {
      uni.showModal({
        title: '确认清理',
        content: '此操作将清除所有本地数据，无法恢复，确定继续吗？',
        success: (res) => {
          if (res.confirm) {
            try {
              uni.clearStorageSync()
              uni.showToast({
                title: '数据已清理',
                icon: 'success'
              })
              this.loadUserData()
            } catch (e) {
              uni.showToast({
                title: '清理失败',
                icon: 'error'
              })
            }
          }
        }
      })
      this.closeDataPopup()
    },
    
    // 显示关于信息
    showAbout() {
      uni.showModal({
        title: '关于情绪大师',
        content: '版本：1.0.0\n一款专注于情绪管理的应用\n帮助你更好地了解和管理情绪',
        showCancel: false
      })
    }
  }
}
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding-bottom: 100rpx;
}

/* 用户信息卡片 */
.user-card {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  margin: 30rpx;
  border-radius: 24rpx;
  padding: 40rpx;
  color: white;
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 120rpx;
  height: 120rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 30rpx;
}

.avatar-text {
  font-size: 60rpx;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 36rpx;
  font-weight: 600;
  display: block;
  margin-bottom: 10rpx;
}

.user-desc {
  font-size: 28rpx;
  opacity: 0.9;
}

.user-stats {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 32rpx;
  font-weight: 600;
  display: block;
}

.stat-label {
  font-size: 24rpx;
  opacity: 0.8;
}

/* 成就徽章 */
.achievement-section {
  margin: 30rpx;
  background: white;
  border-radius: 24rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 30rpx;
}

.badge-list {
  white-space: nowrap;
}

.badge-item {
  display: inline-block;
  text-align: center;
  margin-right: 30rpx;
  opacity: 0.4;
  transition: all 0.3s ease;
}

.badge-item.unlocked {
  opacity: 1;
}

.badge-icon {
  width: 100rpx;
  height: 100rpx;
  background: var(--bg-secondary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15rpx;
}

.badge-item.unlocked .badge-icon {
  background: linear-gradient(135deg, var(--accent-color) 0%, var(--warning-color) 100%);
}

.badge-emoji {
  font-size: 48rpx;
}

.badge-name {
  font-size: 24rpx;
  color: var(--text-secondary);
  display: block;
}

.badge-item.unlocked .badge-name {
  color: var(--text-primary);
  font-weight: 600;
}

/* 功能菜单 */
.menu-section {
  margin: 30rpx;
  background: white;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 40rpx 30rpx;
  border-bottom: 1rpx solid var(--border-color);
  transition: all 0.3s ease;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item:active {
  background: var(--bg-secondary);
}

.menu-icon {
  width: 80rpx;
  height: 80rpx;
  background: var(--bg-secondary);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 30rpx;
}

.menu-icon .iconfont {
  font-size: 40rpx;
}

.menu-content {
  flex: 1;
}

.menu-title {
  font-size: 32rpx;
  color: var(--text-primary);
  display: block;
  margin-bottom: 8rpx;
}

.menu-desc {
  font-size: 26rpx;
  color: var(--text-secondary);
}

.menu-arrow {
  color: var(--text-tertiary);
}

.menu-arrow .iconfont {
  font-size: 32rpx;
}

.menu-switch {
  transform: scale(0.8);
}

/* 数据管理弹窗 */
.data-popup {
  background: white;
  border-radius: 24rpx 24rpx 0 0;
  padding: 40rpx 30rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 600;
  color: var(--text-primary);
}

.popup-close {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup-close .iconfont {
  font-size: 32rpx;
  color: var(--text-tertiary);
}

.popup-content {
  padding-top: 20rpx;
}

.data-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid var(--border-color);
}

.data-item:last-child {
  border-bottom: none;
}

.data-title {
  font-size: 32rpx;
  color: var(--text-primary);
  display: block;
  margin-bottom: 10rpx;
}

.data-desc {
  font-size: 28rpx;
  color: var(--text-secondary);
}

/* 图标字体 */
.iconfont {
  font-family: 'iconfont';
}
</style>